<!--
	作者：offline
	时间：2019-04-03
	描述：模板管理
-->
<template>
	<div class="m-view-template m-window">
		<div class="m-condition">
			<el-row :gutter="10">
				<el-form ref="headerRuleForm" label-width="70px" :inline-message="true" label-position="left">
					<el-col :span="5">
						<el-form-item label="编码" class="rightItem">
							<el-input v-model="searchInfo.code" placeholder="请输入模板编码" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="5">
						<el-form-item label="模板名称" class="rightItem">
							<el-input v-model="searchInfo.name" placeholder="请输入模板名称" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="4">
						<el-form-item label="创建人" class="rightItem">
							<el-input v-model="searchInfo.creator" placeholder="请输入创建人" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="2">
						<el-button type="primary" @click="search(1)" :disabled="btnDis">查询</el-button>
					</el-col>
					<el-col :span="2">
						<el-button type="primary" @click="editTemplate('add')" :disabled="btnDis">新增</el-button>
					</el-col>
					<el-col :span="2">
						<el-button type="primary" @click="editTemplate('edit')" :disabled="btnDis">编辑</el-button>
					</el-col>
					<el-col :span="2">
						<el-button type="primary" @click="downLoadFile()" :disabled="btnDis">下载</el-button>
					</el-col>
					<el-col :span="2">
						<el-button type="primary" @click="deleteTemplate" :disabled="btnDis">删除</el-button>
					</el-col>
				</el-form>
			</el-row>
		</div>
		<div class="m-agTable m-bottom m-top2" style="top:50px;">
			<agGridComponents
				ref="agGridComponent"
				:getGridOptions="gridOptions"
				:getColumnDefs="columnDefs"
				:isColFit="true"
			></agGridComponents>
		</div>
		<div class="m-page">
			<el-pagination
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				@prev-click="handlePrevClick"
				@next-click="handleNextClick"
				:current-page="pageInfo.currentPage"
				:page-sizes="[30,50,100,150,200]"
				:page-size="pageInfo.pageSize"
				layout="total, sizes, prev, pager, next, jumper"
				:total="pageInfo.total"
			></el-pagination>
		</div>
		<!-- 模板上传弹窗 -->
		<el-dialog
			:title="title"
			:visible.sync="dialogVisible"
			v-if="dialogVisible"
			width="50%"
			:before-close="handleClose"
			v-dialogDrag
			:close-on-click-modal="false"
			:close-on-press-escape="false"
			id="container"
		>
			<el-form
				:model="ruleForm"
				ref="ruleForm"
				label-width="100px"
				class="demo-ruleForm"
				:rules="rules"
			>
				<el-form-item label="模板编码" prop="code">
					<el-input v-model="ruleForm.code" placeholder="请输入模板编码" clearable></el-input>
				</el-form-item>
				<el-form-item label="模板名称" prop="name">
					<el-input v-model="ruleForm.name" placeholder="请输入模板名称" clearable></el-input>
				</el-form-item>
				<el-form-item label="模板版本" prop="version">
					<el-input v-model="ruleForm.version" placeholder="请输入模板版本" clearable></el-input>
				</el-form-item>
			</el-form>
			<!-- <el-upload
        class="upload-demo"
        :action="upload_url"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :on-change="fileChange"
        :on-exceed="handleExceed"
        :before-remove="beforeRemove"
        :limit="1"
        :data="userInfo"
        :multiple="true"
        :show-file-list="true"
        :onSuccess="uploadSuccess"
        :before-upload="beforeAvatarUpload"
        :auto-upload="true"
        accept=".pdf, .grf, .xlsx, .xls"
        ref="upload"
      >
        <el-button size="small" type="primary">上传模板</el-button>
        <span
          slot="tip"
          class="el-upload__tip"
          style="padding-left:10px;"
        >只能上传.pdf/.grf/.xls/.xlsx文件，且不超过20MB</span>
			</el-upload>-->
			<lessoUploader
				:baseUrl="baseUrl"
				:userInfo="userInfo"
				:deleteBtn="true"
				@fileAdded="fileAdded"
				@fileRemoved="fileRemoved"
				@fileSuccess="fileSuccess"
				@overSize="overSizeHandler"
				@invalidFileType="onInvalidFile"
				@fileError="fileError"
				@fileExceed="fileExceed"
				:accept="'.xls,.xlsx,.pdf,.grf'"
				:maxSize="20971520"
				:multiple="true"
				:limits="1"
				:allowDuplicateUploads="false"
				@deleteFile="onFileDelete"
			>
				<div slot="upload-btn">
					<div class="slot_btn">选择附件</div>
				</div>
			</lessoUploader>
			<div v-if="isFiles">
				<div class="uploaded-files" v-for="(file,index) in template" :key="index">
					<div>{{file.name}}</div>
					<span>{{file.size|changeSize}}</span>
					<span>已上传</span>
				</div>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button @click="handleClose">取消</el-button>
				<el-button type="primary" @click="saveTemplate" :disabled="saveBtndis">保存</el-button>
				<!-- <el-button type="primary">保存并提交</el-button> -->
			</span>
		</el-dialog>
	</div>
</template>

<script>
import _Api from "@/api";
import localeText from "@/i18n/agGridText";
import lessoUploader from 'lesso-file-upload/lessoUploader';
import agGridComponents from "@/components/agGridComponents.js"
import downLoadFileFunc from "@/public/downLoadFile"
import apienv from '@/api/env'
import Msg from '@/public/message.js'
import constant from "@/public/constant";
/**
 * @group templateManager
 * 模板管理
*/
export default {
	name: "templateManager",
	data () {
		return {
			btnDis: false,
			dialogVisible: false,
			isFiles: false,
			saveBtndis: false,
			title: '',
			//查询条件   
			searchInfo: {
			},
			//新增/编辑表单数据   
			ruleForm: {
				code: '',
				name: '',
				version: ''
			},
			//分页信息   
			pageInfo: {
				pageSize: 30,
				currentPage: 1,
				total: 0
			},
			userInfo: {
				userName: this.$global.user.employeeName,
				userId: this.$global.user.id,
				groupName: 'SRM'
			},
			baseUrl: apienv[constant.appenv].srm + 'uploadFastdfs/',
			upload_url: this.$uploadUrl,
			fileList: [],
			rules: {
				code: [{ required: true, message: '请输入模板编码', trigger: 'blur' }],
				name: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
				version: [{ required: true, message: '请输入模板版本', trigger: 'blur' }]
			},
			template: [],
			rowData: []
		}
	},
	created () { },
	beforeMount () {
		this.gridOptions = {
			context: {
				componentParent: this
			},
			rowSelection: "multiple",
			enableColResize: true,
			localeText: localeText,
			suppressRowClickSelection: true,
			//   getContextMenuItems: '',
			onGridReady: function (params) {
				// params.api.sizeColumnsToFit();
			}
		}
		this.columnDefs = [
			{ headerName: "模板编码", field: "code", width: 150, tooltipField: 'code', checkboxSelection: true },
			{ headerName: "模板名称", field: "name", width: 160, tooltipField: 'name' },
			{ headerName: "模板地址", field: "url", width: 180, tooltipField: 'url' },
			{ headerName: "模板版本号", field: "version", width: 100 },
			{ headerName: "创建人", field: "creator", width: 100 },
			{
				headerName: "创建日期",
				field: "createDate",
				width: 100,
				cellRenderer: function (params) {
					if (params.value) {
						return new Date(params.value).Format("yyyy-MM-dd")
					}
				}
			},
			{ headerName: "修改人", field: "modifyer", width: 100 },
			{
				headerName: "修改日期",
				field: "modifyDate",
				width: 100,
				cellRenderer: function (params) {
					if (params.value) {
						return new Date(params.value).Format("yyyy-MM-dd");
					}
				}
			}
		]
	},
	mounted () {
		this.search();
	},
	methods: {
		//   查询模板列表
		search (flag) {
			if (flag) this.pageInfo.current = 1
			const { currentPage, pageSize } = this.pageInfo
			let params = {
				current: currentPage,
				size: pageSize
			}
			const { code, name, creator } = this.searchInfo
			if (code || creator) {
				let eqParams = {
					code,
					creator
				}
				this.$set(params, 'eqParams', eqParams)
			}
			if (name) {
				let likeParams = { name }
				this.$set(params, 'likeParams', likeParams)
			}
			this.btnDis = true
			this.$refs.agGridComponent.loading = true;
			_Api.getTemplateList(params).then((res) => {
				this.$refs.agGridComponent.loading = false;
				this.btnDis = false
				let data = res.data
				if (data.code == 1) {
					this.rowData = data.rows
					this.pageInfo.total = data.total
					this.$refs.agGridComponent.gridOptions.api.setRowData(this.rowData)
				} else {
					Msg.showErrorMsg(data.info)
					this.btnDis = false
				}
			}).catch((err) => {
				Msg.showErrorMsg(err.data.message)
				this.$refs.agGridComponent.loading = false
				this.btnDis = false
			})
		},
		handleSizeChange (params) {
			this.pageInfo.currentPage = 1;
			this.pageInfo.pageSize = params;
			this.search();
		},
		handleCurrentChange (params) {
			if (this.textChange === 1)
				this.currentPage = 1;
			else
				this.pageInfo.currentPage = params;
			this.search();
		},
		handlePrevClick (params) {
			if (this.textChange === 1)
				this.pageInfo.currentPage = 1;
			else
				this.pageInfo.currentPage = params;
		},
		handleNextClick (params) {
			if (this.textChange === 1)
				this.pageInfo.currentPage = 1;
			else
				this.pageInfo.currentPage = params;
		},
		// 新增或编辑模板
		editTemplate (type) {
			if (type == "add") {
				this.dialogVisible = true
				this.isFiles = false
				this.title = '新增模板'
				this.ruleForm = {
					code: '',
					name: '',
					version: ''
				}
				this.template = []
			} else {
				let rows = this.$refs.agGridComponent.gridOptions.api.getSelectedRows();
				if (rows.length <= 0) {
					this.$alert("提示：请选择一条你想要编辑的数据", {
						showClose: false,
						confirmButtonText: "确定",
						customClass: "alertPrompt"
					});
					return;
				} else if (rows.length > 1) {
					this.$alert("提示：每次只能编辑一条数据！", {
						showClose: false,
						confirmButtonText: "确定",
						customClass: "alertPrompt"
					});
					return;
				}
				const { size, url, fileName, md5 } = rows[0]
				this.title = '编辑模板'
				this.dialogVisible = true
				this.isFiles = true
				this.ruleForm = {
					code: rows[0].code,
					name: rows[0].name,
					version: rows[0].version,
					id: rows[0].id
				}
				this.template = [
					{
						name: fileName,
						size,
						url,
						md5
					}
				]
			}
		},
		// 删除模板
		deleteTemplate () {
			let rows = this.$refs.agGridComponent.gridOptions.api.getSelectedRows();
			if (rows.length <= 0) {
				this.$alert("提示：请选择一条你想要删除的数据", {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				});
				return;
			}
			this.$confirm("是否确认删除该数据？", "消息提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				distinguishCancelAndClose: true
			}).then(() => {
				let params = {
					id: rows[0].id
				}
				_Api.deleteTemplate(params).then((res) => {
					let data = res.data
					if (data.code == 1) {
						this.$message({
							message: '删除成功',
							type: 'success'
						})
						this.search()
					} else {
						Msg.showErrorMsg(data.info)
					}
				})
					.catch((err) => {
						Msg.showErrorMsg(err.data.message)
					})
			}).catch(() => {
				this.$message({
					message: '已取消删除',
					type: 'info'
				})
			})
		},
		// 关闭弹窗
		handleClose () {
			this.dialogVisible = false
			this.$refs.ruleForm.resetFields()
		},
		// 文件通过检查回调
		fileAdded (file) {
			this.isFiles = false
		},
		// 文件已移除回调
		fileRemoved (file, res) {
			console.log('删除文件', file)
			if (res.code == 200) {
				this.template.forEach((ele, index) => {
					if (ele.md5 == file.md5) {
						this.template.splice(index, 1)
					}
				});
			}
		},
		// 文件上传成功回调
		fileSuccess (file, message) {
			this.template = []
			const { size, viewPath, name, md5 } = file
			this.template.push({
				size,
				viewPath,
				name,
				md5,
				creator: this.$global.user.loginName,
				creatorId: this.$global.user.id,
			})
		},
		// 点击已上传文件回调
		handlePreview (file) {
			//console.log(file);
		},
		// 删除文件回调
		handleRemove (file, fileList) {
		},
		// 删除文件前回调
		beforeRemove (file, fileList) {
			// return this.$confirm(`确定移除 ${ file.name }？`).catch(()=>{});
		},
		// 文件状态改变回调
		fileChange (file, fileList) {
			this.isFiles = false
		},
		// 文件超出上传个数
		handleExceed (files, fileList) {
			this.$message({
				message: '文件超出个数！',
				type: 'warning'
			});
		},
		// 文件上传成功
		uploadSuccess (res, file, fileList) {
			if (res.code == 1) {
				this.template = []
				const { fileName, orgName } = res.rows[0]
				this.template.push({
					size: file.size,
					url: fileName,
					name: orgName,
					creator: this.$global.user.loginName,
					creatorId: this.$global.user.id,
				})
			}
		},
		// 文件上传前
		beforeAvatarUpload (file) {
			let fileType = file.name.substring(file.name.lastIndexOf('.') + 1).toLocaleLowerCase()
			if (fileType != "grf" && fileType != "pdf" && fileType != "xls" && fileType != "xlsx") {
				this.$message({
					message: '上传文件类型只支持.grf/.pdf/.xlsx/.xls！',
					type: 'warning'
				});
				return false;
			}
			const size = file.size / 1024 / 1024 < 20;
			if (!size) {
				this.$message({
					message: '上传模板大小不能超过 20MB!',
					type: 'warning'
				});
				return false;
			}
		},
		// 删除文件
		onFileDelete (file, callback) {
			this.$confirm("是否删除该附件？", "消息提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				distinguishCancelAndClose: true
			}).then(() => {
				callback(true)
			}).catch(() => {
				this.$message({
					message: '已取消删除',
					type: 'info'
				})
			})
		},
		// 文件超出大小回调
		overSizeHandler (file) { // 文件过大回调
			this.$message.warning("选择的文件大小不能超过20M")
		},
		//文件类型不合法
		onInvalidFile (file) {
			this.$message.warning('只能上传.xls,.xlsx,.pdf,.grf类型文件')
		},
		// 文件上传失败回调
		fileError (file, message, chunk) {
			message = JSON.parse(message)
			this.$message.error(message.msg);
		},
		//文件个数超出限制
		fileExceed (files, fileList) {
			this.$message.warning('上传文件个数超出限制,最多只能上传1个文件')
		},
		// 保存文件信息
		saveTemplate () {
			if (this.template.length == 0) {
				this.$message({
					message: '请选择模板上传！',
					type: 'error'
				})
				return
			}
			this.$refs["ruleForm"].validate((valid) => {
				if (valid) {
					const { size, name, viewPath, md5 } = this.template[0]
					let params = {
						...this.ruleForm,
						url: viewPath,
						md5,
						groupName: 'SRM',
						size,
						fileName: name
					}
					this.saveBtndis = true
					if (this.title == '新增模板') {
						params.creator = this.userInfo.userName
						params.creatorId = this.userInfo.userId
					} else {
						params.modifyer = this.userInfo.userName
						params.modifyerId = this.userInfo.userId
					}
					_Api.saveTemplate(params).then((res) => {
						let data = res.data
						this.saveBtndis = false
						if (data.code == 1) {
							this.$message({
								message: '保存成功！',
								type: 'success'
							})
							this.handleClose()
							this.search()
						} else {
							Msg.showErrorMsg(data.info)
						}
					}).catch((err) => {
						this.saveBtndis = false
						Msg.showErrorMsg(err.data.message)
					})
				}
			})
		},
		/**
		 * @vuese
		 * 下载模板文件
		*/
		downLoadFile () {
			let rows = this.$refs['agGridComponent'].gridOptions.api.getSelectedRows();
			let obj = {};
			if (rows.length == 0) {
				Msg.showPopMsg('请选择你需要下载的模板文件!')
				return
			} else if (rows.length > 1) {
				Msg.showPopMsg('每次只能选择一条文件进行下载!')
				return
			}
			obj = {
				viewPath: rows[0].url,
				groupName: rows[0].groupName
			}
			downLoadFileFunc(obj, rows[0].fileName)
		},
	},
	components: {
		lessoUploader,
		agGridComponents
	},
	watch: {
		name (value) {
			if (value)
				this.textChange = 1;
			else
				this.textChange = 0;
		}
	},
	filters: {
		// 文件大小转换
		changeSize (limit) {
			let size = "";
			if (limit != undefined) {
				limit = parseInt(limit);
				if (limit < 1 * 1024) {
					//如果小于0.1KB转化成B
					size = limit.toFixed(2) + "B";
				} else if (limit < 1 * 1024 * 1024) {
					//如果小于0.1MB转化成KB
					size = (limit / 1024).toFixed(2) + "KB";
				} else if (limit < 1 * 1024 * 1024 * 1024) {
					//如果小于0.1GB转化成MB
					size = (limit / (1024 * 1024)).toFixed(2) + "MB";
				} else {
					//其他转化成GB
					size = (limit / (1024 * 1024 * 1024)).toFixed(2) + "GB";
				}
			}
			let sizestr = size + "";
			let len = sizestr.indexOf(".");
			let dec = sizestr.substr(len + 1, 2);
			if (dec == "00") {
				//当小数点后为00时 去掉小数部分
				return sizestr.substring(0, len) + sizestr.substr(len + 3, 2);
			}
			return sizestr;
		}
	}
}
</script>
<style lang="less" scoped>
.uploaded-files {
	display: flex;
	justify-content: space-between;
	padding: 5px 0;
	margin-left: 16px;
}
</style>